<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="机器人名称" prop="robotName">
        <el-input
          v-model="queryParams.robotName"
          placeholder="请输入机器人名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="语音控制" prop="voiceControl">
        <el-select v-model="queryParams.voiceControl" placeholder="请选择语音控制" clearable size="small">
          <el-option
            v-for="dict in voiceControlOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="播报者" prop="announcer">
        <el-select v-model="queryParams.announcer" placeholder="请选择播报者" clearable size="small">
          <el-option
            v-for="dict in announcerOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tenant:robotSetting:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tenant:robotSetting:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tenant:robotSetting:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tenant:robotSetting:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="robotSettingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="机器人编号" align="center" prop="robotId" />
      <el-table-column label="关联账号" align="center" prop="userId" :formatter="formatUserName"/>
      <el-table-column label="机器人名称" align="center" prop="robotName" />
      <el-table-column label="语音控制" align="center" prop="voiceControl">
        <template slot-scope="scope">
              <el-switch
                v-model="scope.row.voiceControl"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
      </el-table-column>
      <el-table-column label="播报者" align="center" prop="announcer" :formatter="announcerFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tenant:robotSetting:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tenant:robotSetting:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改机器人设置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="关联账号" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择关联账号">
             <el-option
              v-for="item in robotUserMap.keys()"
              :key="item"
              :label="robotUserMap.get(item)"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机器人名称" prop="robotName">
          <el-input v-model="form.robotName" placeholder="请输入机器人名称" style="width:217px"/>
        </el-form-item>
        <el-form-item label="语音控制" prop="voiceControl">
          <el-select v-model="form.voiceControl" placeholder="请选择语音控制">
            <el-option
              v-for="dict in voiceControlOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>

          </el-select>
        </el-form-item>
        <el-form-item label="播报者" prop="announcer">
          <el-select v-model="form.announcer" placeholder="请选择播报者">
            <el-option
              v-for="dict in announcerOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRobotSetting, getRobotSetting, delRobotSetting, addRobotSetting, updateRobotSetting } from "@/api/tenant/robotSetting";
import {listTenantRobotUser } from "@/api/system/user";
export default {
  name: "RobotSetting",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 机器人设置表格数据
      robotSettingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 语音控制字典
      voiceControlOptions: [],
      // 播报者字典
      announcerOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        robotName: null,
        voiceControl: null,
        announcer: null,
      },
       robotUserMap:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "关联账号不能为空", trigger: "change" }
        ],
        robotName: [
          { required: true, message: "机器人名称不能为空", trigger: "blur" }
        ],
        voiceControl: [
          { required: true, message: "语音控制不能为空", trigger: "change" }
        ],
        announcer: [
          { required: true, message: "播报者不能为空", trigger: "change" }
        ]
      }
    };
  },

  created() {
    this.getList();
    this.getUserMap();
    this.getDicts("tenant_robot_voice_control").then(response => {
      this.voiceControlOptions = response.data;
    });
    this.getDicts("tenant_robot_announcer").then(response => {
      this.announcerOptions = response.data;
    });
    
  },
  methods: {
    handleStatusChange(row){
      let text = row.voiceControl===1?'开启语音控制':'停用语音控制';
      this.$confirm('确定"'+row.robotName+'" 要 "'+text +'"吗?',"警告",{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type:"warning"
      }).then(()=>{
        return updateRobotSetting({robotId:row.robotId,voiceControl:row.voiceControl})
      }).then(()=>{
        this.msgSuccess(text + "成功");
      }).catch(()=>{
         row.voiceControl = row.voiceControl==0?1:0;
      })
     
    },
    /** 查询机器人设置列表 */
    getList() {
      this.loading = true;
      listRobotSetting(this.queryParams).then(response => {
        this.robotSettingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 语音控制字典翻译
    voiceControlFormat(row, column) {
      return this.selectDictLabel(this.voiceControlOptions, row.voiceControl);
    },
    // 播报者字典翻译
    announcerFormat(row, column) {
      return this.selectDictLabel(this.announcerOptions, row.announcer);
    },
    // 机器人用户名称
     formatUserName(row){
      return this.robotUserMap.get(row.userId);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        robotId: null,
        userId: null,
        robotName: null,
        voiceControl: null,
        announcer: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.robotId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加机器人设置";
    },
    /** 获取机器人用户 */
    getUserMap(){
      let map = new Map();
      listTenantRobotUser().then((result)=>{
       result.rows.forEach(element => {
          map.set(element.userId, element.userName);
        });
        this.robotUserMap = map;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const robotId = row.robotId || this.ids
      getRobotSetting(robotId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改机器人设置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.robotId != null) {
            updateRobotSetting(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRobotSetting(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const robotIds = row.robotId || this.ids;
      this.$confirm('是否确认删除机器人设置编号为"' + robotIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRobotSetting(robotIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('tenant/robotSetting/export', {
        ...this.queryParams
      }, `tenant_robotSetting.xlsx`)
    }
  }
};
</script>